package com.hioove.netty;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
public class NettyTest {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch=new CountDownLatch(1);
        ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(2);
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(2, Integer.MAX_VALUE, 2, TimeUnit.SECONDS, queue, new ThreadPoolExecutor.CallerRunsPolicy());
        for (int i = 0; i < 99; i++) {
            threadPoolExecutor.submit(() -> {
                log.info("******** " + Thread.currentThread().getName());
                try {
                    latch.await();
                } catch (InterruptedException e) {
                }
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(5000, TimeUnit.MILLISECONDS)
                        .build();
                Request loginRequest = new Request.Builder()
                        .url("http://localhost:9090")
                        .get()
                        .build();
                try {
                    Response response = client.newCall(loginRequest).execute();
                    log.info("******** " + response.body().string());
                } catch (Exception e) {
                }
            });
        }
        latch.countDown();
        TimeUnit.SECONDS.sleep(3);
        System.out.println(threadPoolExecutor.isShutdown());
        System.out.println(threadPoolExecutor.isTerminated());
        System.out.println(threadPoolExecutor.isTerminating());
        log.info(IntStream.iterate(0, operand -> operand + 1).limit(10).mapToObj(value -> "*").collect(Collectors.joining()));
        threadPoolExecutor.shutdown();
        System.out.println(threadPoolExecutor.isShutdown());
        System.out.println(threadPoolExecutor.isTerminated());
        System.out.println(threadPoolExecutor.isTerminating());
        log.info(IntStream.rangeClosed(0, 5).limit(10).mapToObj(value -> "*").collect(Collectors.joining()));
        threadPoolExecutor.shutdownNow();
        System.out.println(threadPoolExecutor.isShutdown());
        System.out.println(threadPoolExecutor.isTerminated());
        System.out.println(threadPoolExecutor.isTerminating());
        log.info(IntStream.rangeClosed(0, 5).limit(10).mapToObj(value -> "*").collect(Collectors.joining()));
    }
}
